package rsj.api.org.importdata;

import com.rlyy.aibase.db.Dbink;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.Node;
import common.exec.RsjIllegalArgueException;
import common.util.BoxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.org.entity.ReImportTestDataEntity;
import rsj.api.org.importdata.entity.ExecutionImportTestData;
import rsj.api.user.BaseLink;
import rsj.db.PostgresqlConn;
import common.util.validator.ParameterConversionCheck;
import common.util.QueryRunnerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Set;

/**
 * 再次上传
 *
 * @author yuanqinglong
 * @since 2021/3/10 15:22
 */
@RestController
public class UploadAgainController extends BaseLink {
    private static final Logger logger = LoggerFactory.getLogger(UploadAgainController.class);


    /**
     * 再次上传
     *
     * @param box 参数
     * @return 。
     * @throws SQLException 异常
     */
    @Override
    @RequestMapping(value = "rsj_upload_again")
    public Box executeLink(Box box) throws SQLException {
        ReImportTestDataEntity reImportTestDataEntity = (ReImportTestDataEntity) ParameterConversionCheck.parameterConversionCheckFastFail(box, ReImportTestDataEntity.class);
        this.reUpload(reImportTestDataEntity);
        return BoxUtil.successBox(box);
    }


    /**
     * 再次上传
     *
     * @param reImportTestDataEntity 重新上传字段
     */
    private void reUpload(ReImportTestDataEntity reImportTestDataEntity) {
        this.checkCost(reImportTestDataEntity);
        String isCost = ImportEasyExcelInvoke.COST_CODE_TO_CHINESE.get(reImportTestDataEntity.getLogIscost());
        reImportTestDataEntity.setLogIscost(isCost);
        String isDsCost = ImportEasyExcelInvoke.COST_CODE_TO_CHINESE.get(reImportTestDataEntity.getLogDscost());
        reImportTestDataEntity.setLogDscost(isDsCost);
        Connection connection = PostgresqlConn.getConnection();
        String logId = reImportTestDataEntity.getLogId();
        try {
            String orgId = this.queryOrgId(logId, connection);
            reImportTestDataEntity.setLogStoragetime(LocalDateTime.now());
            // TODO: 2021/3/11 校验
            String addSqlStatement = ExecutionImportTestData.assemblyTestLogSql(Collections.singletonList(reImportTestDataEntity), orgId);
            int update = QueryRunnerFactory.getQueryRunner().update(connection, addSqlStatement);
            if (update > 0) {
                // 删除失败日志
                this.uploadAgainSuccessfullyDeleteFailedLog(logId, connection);
            }
        } catch (SQLException e) {
            logger.error("再次上传失败、日志id：{}", logId, e);
            throw new RsjIllegalArgueException("再次上传失败");
        } finally {
            Dbink.close(connection);
        }
    }


    /**
     * 再次上传成功删除失败日志
     *
     * @param logId 失败日志id
     */
    private void uploadAgainSuccessfullyDeleteFailedLog(String logId, Connection connection) {
        String sql = "DELETE FROM sys.oper_test_fail_log WHERE log_id = '" + logId + "'";
        try {
            int delete = QueryRunnerFactory.getQueryRunner().update(connection, sql);
        } catch (SQLException e) {
            logger.error("删除失败日志异常、日志id：{}", logId, e);
            throw new RsjIllegalArgueException(e.getMessage());
        }
    }


    /**
     * 查询机构id
     *
     * @param logId      日志id
     * @param connection 数据库连接
     * @return 机构id
     */
    private String queryOrgId(String logId, Connection connection) {
        String sql = " SELECT log_org_id FROM sys.oper_test_fail_log WHERE log_id = '" + logId + "'";
        Node node = QueryRunnerFactory.getQueryRunner().queryLinkNode(connection, sql);
        return node.value();
    }


    /**
     * 校验是否收费格式输入： 是 或 否
     *
     * @param reImportTestDataEntity 入参
     */
    private void checkCost(ReImportTestDataEntity reImportTestDataEntity) {
        Set<String> cost = ImportEasyExcelInvoke.COST_CHINESE_TO_CODE.keySet();
        if (!cost.contains(reImportTestDataEntity.getLogIscost()) || !cost.contains(reImportTestDataEntity.getLogDscost())) {
            throw new RsjIllegalArgueException("是否收费格式错误");
        }
    }
}
